﻿using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace TrafficArchives.Controls
{
    public partial class Inc_Pager : UserControl
    {
        LinkButton btnFirstPage;
        LinkButton btnPreviousPage;
        LinkButton btnNextPage;
        LinkButton btnLastPage;
        LinkButton btnGoPage;
        TextBox txtPage;
        String pageInfo = "共{0}行 每页{1}行 共{2}页";


        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder js = new StringBuilder();
            js.Append("function CheckGotoPage(pageObj, pageCount)\n");
            js.Append("{\n");
            js.Append("    var page = pageObj.value; \n");
            js.Append("    var numericPage = 0; \n");
            js.Append("    if(!IsNumber(page))\n");
            js.Append("    {\n");
            js.Append("        pageObj.value = '';\n");
            js.Append("        alert('请输入数字！');\n");
            js.Append("        return;\n");
            js.Append("    }\n");
            js.Append("    else\n");
            js.Append("    {\n");
            js.Append("        numericPage = parseInt(page);\n");
            js.Append("    }\n");
            js.Append("    if(numericPage < 1 || numericPage > pageCount)\n");
            js.Append("    {\n");
            js.Append("        pageObj.value = '';\n");
            js.Append("        alert('请输入1-' + pageCount + '之间的页码');\n");
            js.Append("        return;\n");
            js.Append("    }\n");
            js.Append("}\n");
            js.Append("function IsNumber(String)\n");
            js.Append("{\n");
            js.Append("var Letters = '1234567890';\n");
            js.Append("var i;\n");
            js.Append("var c;\n");
            js.Append("for( i = 0; i < String.length; i ++ )\n");
            js.Append("{\n");
            js.Append("c = String.charAt( i );\n");
            js.Append("if (Letters.indexOf( c ) ==-1)\n");
            js.Append("{\n");
            js.Append("return false;\n");
            js.Append("}\n");
            js.Append("}\n");
            js.Append("return true;\n");
            js.Append("} \n");
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "CheckGotoPage", js.ToString(), true);

        }

        /// <summary>
        /// 获取页总数。
        /// </summary>
        /// <returns></returns>
        private Int32 GetPageCount()
        {
            Int32 pageCount = 0;
            if (RecordCount == 0)
            {
                return pageCount;
            }
            pageCount = RecordCount / PageSize;
            if (RecordCount % PageSize > 0)
            {
                pageCount++;
            }
            return pageCount;
        }

        protected override void Render(HtmlTextWriter writer)
        {

            LiteralControl space = new LiteralControl("|");
            LiteralControl tableS = new LiteralControl("<table width='100%' style='font-size:12px;' align='center' border='0' cellspacing='0'><tr>\n");
            LiteralControl cellS = new LiteralControl("<td>");
            LiteralControl cellSRight = new LiteralControl("<td align='right'>");
            LiteralControl cellE = new LiteralControl("</td>");
            LiteralControl tableE = new LiteralControl("</tr></table>\n");

            // 表格开始
            //
            tableS.RenderControl(writer);
            // 输出分页信息
            //
            if (PageInfoVisible)
            {
                LiteralControl info = new LiteralControl(String.Format(pageInfo, RecordCount, PageSize, GetPageCount()));
                cellS.RenderControl(writer);
                info.RenderControl(writer);
                cellE.RenderControl(writer);

            }
            // 中间空单元格
            //
            cellS.RenderControl(writer);
            cellE.RenderControl(writer);
            cellSRight.RenderControl(writer);

            if (FirstPageVisible || PreviousPageVisible || NextPageVisible || LastPageVisible)
            {
                // 输出按钮。
                //
                LiteralControl lc1 = new LiteralControl("[");
                lc1.RenderControl(writer);
                if (FirstPageVisible)
                {
                    btnFirstPage.Enabled = IsForward;
                    btnFirstPage.RenderControl(writer);
                    space.RenderControl(writer);
                }
                if (PreviousPageVisible)
                {
                    btnPreviousPage.Enabled = IsForward;
                    btnPreviousPage.RenderControl(writer);
                    space.RenderControl(writer);
                }
                if (NextPageVisible)
                {
                    btnNextPage.Enabled = IsBack;
                    btnNextPage.RenderControl(writer);
                    space.RenderControl(writer);
                }

                if (LastPageVisible)
                {
                    btnLastPage.Enabled = IsBack;
                    btnLastPage.RenderControl(writer);
                    LiteralControl lc2 = new LiteralControl("]&nbsp;");
                    lc2.RenderControl(writer);
                }
            }

            if (GotoPageVisible)
            {
                LiteralControl lc3 = new LiteralControl("第");
                lc3.RenderControl(writer);
                txtPage.Attributes.Add("onclick", "this.select();");
                txtPage.Attributes.Add("onkeyup", "CheckGotoPage(this, " + GetPageCount() + ")");
                txtPage.Text = CurrentPageIndex.ToString();
                txtPage.RenderControl(writer);

                LiteralControl lc4 = new LiteralControl("页&nbsp;");
                lc4.RenderControl(writer);
                btnGoPage.Enabled = GetPageCount() > 1;
                btnGoPage.RenderControl(writer);
            }
            cellE.RenderControl(writer);
            // 表格结束
            //
            tableE.RenderControl(writer);

        }

        /// <summary>
        /// 创建分页按钮控件
        /// </summary>
        protected override void CreateChildControls()
        {
            Controls.Clear();
            // 第一页
            //
            btnFirstPage = new LinkButton();
            btnFirstPage.EnableViewState = false;
            btnFirstPage.ID = base.ID + "btnFirstPage";
            btnFirstPage.Text = "首页";
            btnFirstPage.CommandArgument = "1";
            btnFirstPage.Click += new EventHandler(OnPageIndexChanged);
            Controls.Add(btnFirstPage);

            // 上一页
            //
            btnPreviousPage = new LinkButton();
            btnPreviousPage.EnableViewState = false;
            btnPreviousPage.ID = base.ID + "previousPage";
            btnPreviousPage.Text = "上页";
            btnPreviousPage.CommandArgument = (CurrentPageIndex - 1).ToString();
            btnPreviousPage.Click += new EventHandler(OnPageIndexChanged);
            Controls.Add(btnPreviousPage);

            // 下一页
            //
            btnNextPage = new LinkButton();
            btnNextPage.EnableViewState = false;
            btnNextPage.ID = base.ID + "btnNextPage";
            btnNextPage.Text = "下页";
            btnNextPage.CommandArgument = (CurrentPageIndex + 1).ToString();
            btnNextPage.Click += new EventHandler(OnPageIndexChanged);
            Controls.Add(btnNextPage);

            // 最后页
            //
            btnLastPage = new LinkButton();
            btnLastPage.EnableViewState = false;
            btnLastPage.ID = base.ID + "btnLastPage";
            btnLastPage.Text = "尾页";
            btnLastPage.CommandArgument = GetPageCount().ToString();
            btnLastPage.Click += new EventHandler(OnPageIndexChanged);
            Controls.Add(btnLastPage);

            // 页码
            //
            txtPage = new TextBox();
            txtPage.ID = base.ID + "txtPage";
            txtPage.EnableViewState = false;
            txtPage.Columns = 2;
            txtPage.MaxLength = 6;
            txtPage.CssClass = "TextBoxStyles";
            txtPage.Text = String.Empty;
            Controls.Add(txtPage);
            // 跳转页
            //
            btnGoPage = new LinkButton();
            btnGoPage.EnableViewState = false;
            btnGoPage.ID = base.ID + "btnGoPage";
            btnGoPage.Text = "GO";
            btnGoPage.Click += new EventHandler(OnGotoPageChanged);
            Controls.Add(btnGoPage);

        }

        /// <summary>
        /// 声明公有分页事件， 以便向上传递分页事件。
        /// </summary>
        public event EventHandler PageIndexChanged;

        /// <summary>
        /// LinkButton 按钮事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPageIndexChanged(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            if (lb.CommandArgument.Trim().Replace(",", "") == String.Empty)
            {
                return;
            }
            CurrentPageIndex = Convert.ToInt32(lb.CommandArgument);

            if (PageIndexChanged != null)
            {
                PageIndexChanged(sender, e);
            }
        }

        /// <summary>
        /// 跳转页事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnGotoPageChanged(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            Int32 page = 1;
            try
            {
                page = Convert.ToInt32(txtPage.Text.Trim());
            }
            catch
            {
            }
            if (page > 0 && page <= GetPageCount())
            {
                lb.CommandArgument = page.ToString();
                CurrentPageIndex = page;
                PageIndexChanged(sender, e);
            }
        }

        #region 分页属性相关

        /// <summary>
        /// 记录总数。
        /// </summary>
        public Int32 RecordCount
        {
            set
            {

                ViewState["RecordCount" + base.ID] = value;

            }
            get
            {
                if (ViewState["RecordCount" + base.ID] == null)
                {
                    return 0;
                }
                return Convert.ToInt32(ViewState["RecordCount" + base.ID]);
            }
        }

        /// <summary>
        /// 当前页码索引。
        /// </summary>
        public Int32 CurrentPageIndex
        {
            set
            {
                ViewState["CurrentPageIndex" + base.ID] = value;
            }
            get
            {
                if (ViewState["CurrentPageIndex" + base.ID] == null)
                {
                    return 1;
                }
                Int32 currentPageIndex = Convert.ToInt32(ViewState["CurrentPageIndex" + base.ID]);
                if (currentPageIndex < 1)
                {
                    return 1;
                }
                var pageCount = GetPageCount();
                if (pageCount > 0 && currentPageIndex > GetPageCount())
                {
                    return GetPageCount();
                }
                return currentPageIndex;
            }
        }

        /// <summary>
        /// 页大小。
        /// </summary>
        public Int32 PageSize
        {
            set
            {
                ViewState["PageSize" + base.ID] = value;
            }
            get
            {
                if (ViewState["PageSize" + base.ID] == null)
                {
                    int size = 20;
                    var cookie = Request.Cookies["ScreenHeight"];
                    if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                    {
                        int screenHeight;
                        if (Int32.TryParse(cookie.Value, out screenHeight))
                        {
                            size = (screenHeight - 350)/30;
                        }
                    }
                    return size;
                }
                return Convert.ToInt32(ViewState["PageSize" + base.ID]);
            }
        }

        /// <summary>
        /// 是否可后退。
        /// </summary>
        private Boolean IsBack
        {
            get
            {
                return (CurrentPageIndex < GetPageCount()) && (GetPageCount() >= 1);
            }
        }

        /// <summary>
        /// 是否可前进。
        /// </summary>
        private Boolean IsForward
        {
            get
            {
                return (CurrentPageIndex > 1) && (CurrentPageIndex <= GetPageCount());
            }
        }

        /// <summary>
        /// 是否显示第一页按钮
        /// </summary>
        public Boolean FirstPageVisible
        {
            set
            {
                ViewState["FirstPageVisible" + base.ID] = value;
            }
            get
            {
                if (ViewState["FirstPageVisible" + base.ID] != null)
                {
                    return Convert.ToBoolean(ViewState["FirstPageVisible" + base.ID]);
                }
                return true;
            }
        }

        /// <summary>
        /// 是否显示前一页按钮
        /// </summary>
        public Boolean PreviousPageVisible
        {
            set
            {
                ViewState["PreviousPageVisible" + base.ID] = value;
            }
            get
            {
                if (ViewState["PreviousPageVisible" + base.ID] != null)
                {
                    return Convert.ToBoolean(ViewState["PreviousPageVisible" + base.ID]);
                }
                return true;
            }
        }

        /// <summary>
        /// 是否显示后一页按钮。
        /// </summary>
        public Boolean NextPageVisible
        {
            set
            {
                ViewState["NextPageVisible" + base.ID] = value;
            }
            get
            {
                if (ViewState["NextPageVisible" + base.ID] != null)
                {
                    return Convert.ToBoolean(ViewState["NextPageVisible" + base.ID]);
                }
                return true;
            }
        }

        /// <summary>
        /// 是否显示最后页按钮。
        /// </summary>
        public Boolean LastPageVisible
        {
            set
            {
                ViewState["LastPageVisible" + base.ID] = value;
            }
            get
            {
                if (ViewState["LastPageVisible" + base.ID] != null)
                {
                    return Convert.ToBoolean(ViewState["LastPageVisible" + base.ID]);
                }
                return true;
            }
        }

        public Boolean GotoPageVisible
        {
            set
            {
                ViewState["GotoPageVisible" + base.ID] = value;
            }
            get
            {
                if (ViewState["GotoPageVisible" + base.ID] != null)
                {
                    return Convert.ToBoolean(ViewState["GotoPageVisible" + base.ID]);
                }
                return true;
            }
        }

        public Boolean PageInfoVisible
        {
            set
            {
                ViewState["PageInfoVisible" + base.ID] = value;
            }
            get
            {
                if (ViewState["PageInfoVisible" + base.ID] != null)
                {
                    return Convert.ToBoolean(ViewState["PageInfoVisible" + base.ID]);
                }
                return true;
            }
        }

        #endregion
    }
}
